package io.renren.modules.common.controller;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;

import io.renren.common.utils.R;
import io.renren.common.utils.SensitiveWordUtil;
import io.renren.modules.common.entity.DemandSensitiveWordEntity;
import io.renren.modules.common.service.DemandSensitiveWordService;

/**
 * 
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2019-02-25 11:08:59
 */
@RestController
@RequestMapping("common/demandsensitiveword")
public class DemandSensitiveWordController {
	@Autowired
	private DemandSensitiveWordService demandSensitiveWordService;

	/**
	 * 获取所有关键字
	 */
	@RequestMapping("/sensitiveWord")
	public R sensitiveWord() {
		List<String> list = demandSensitiveWordService.sensitiveWord();

		return R.ok().put("data", list);
	}

	/**
	 * 添加关键字
	 */
	@RequestMapping("/addSensitiveWord")
	public R addSensitiveWord(@RequestBody DemandSensitiveWordEntity demandSensitiveWordEntity) {
		demandSensitiveWordService.insert(demandSensitiveWordEntity);
		List<String> list = demandSensitiveWordService.sensitiveWord();
		HazelcastInstance sensitiveWord = Hazelcast.newHazelcastInstance();
		sensitiveWord.getMap("sensitiveWord").put("sensitiveWordList", list);
		return R.ok();
	}

	@SuppressWarnings({ "static-access", "unchecked" })
	@RequestMapping("/checkStr")
	public R checkStr(@RequestBody String string) {
		SensitiveWordUtil sensitiveWordUtil = new SensitiveWordUtil();
		HazelcastInstance sensitiveWordHaze = Hazelcast.newHazelcastInstance();
		List<String> list = (List<String>) sensitiveWordHaze.getMap("sensitiveWord").get("sensitiveWordList");
		if (list.size() == 0) {
			list = demandSensitiveWordService.sensitiveWord();
			List<String> sensitiveWordList = demandSensitiveWordService.sensitiveWord();
			HazelcastInstance sensitiveWord = Hazelcast.newHazelcastInstance();
			sensitiveWord.getMap("sensitiveWord").put("sensitiveWordList", sensitiveWordList);
		}
		Set<String> sensitiveWordSet = new HashSet<>(list);
		sensitiveWordUtil.init(sensitiveWordSet);
		// 是否含有关键字
		boolean result = SensitiveWordUtil.contains(string);
		System.out.println(result);
		result = SensitiveWordUtil.contains(string, SensitiveWordUtil.MinMatchTYpe);
		System.out.println(result);
		// 获取语句中的敏感词
		Set<String> set = SensitiveWordUtil.getSensitiveWord(string);
		set = SensitiveWordUtil.getSensitiveWord(string, SensitiveWordUtil.MinMatchTYpe);
		return R.error().put("msg", "语句中包含敏感词的个数为：" + set.size() + "。包含：" + set);
	}

}
